package com.huijie.core.configuration;

import org.jsets.shiro.config.ShiroProperties;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class CorsFilter implements Filter {

    @Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletResponse response = (HttpServletResponse) res;
		HttpServletRequest request = (HttpServletRequest) req;
		//允许跨域访问
//        String requestOrigin = request.getHeader("Origin");
//        response.setHeader("Access-Control-Allow-Origin", requestOrigin);
		response.setHeader("Access-Control-Allow-Origin", "*");
		//允许请求的方式
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
		//请求缓存时间
		response.setHeader("Access-Control-Max-Age", "3600");
		response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type, jwt_token");
		response.setHeader("Access-Control-Expose-Headers", ShiroProperties.HEADER_JWT);
		String requestMethodOptions = "OPTIONS";
		if (requestMethodOptions.equals(request.getMethod())) {
			response.setStatus(200);
			return;
		}
		chain.doFilter(req, response);
    }

    @Override
	public void init(FilterConfig filterConfig) {}

    @Override
	public void destroy() {}

}